package com.example.mardan.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.mardan.entity.SongciChapter;
import com.example.mardan.entity.SongciDetail;
import com.example.mardan.retrofit.SongciRetrofit;
import com.example.mardan.service.ApiService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SongciViewModel extends ViewModel {
    private ApiService apiService;
    private MutableLiveData<List<SongciChapter.ResultDTO>> chapters;
    private MutableLiveData<SongciDetail.ResultDTO> detail;

    public SongciViewModel() {
        this.apiService = SongciRetrofit.getClient("https://api.jisuapi.com/").create(ApiService.class);
    }

    public LiveData<List<SongciChapter.ResultDTO>> getChapters() {
        if (chapters == null) {
            chapters = new MutableLiveData<>();
            loadChapters();
        }
        return chapters;
    }

    public LiveData<SongciDetail.ResultDTO> getDetail(int detailid) {
        if (detail == null) {
            detail = new MutableLiveData<>();
            loadDetail(detailid);
        }
        return detail;
    }

    private void loadChapters() {
        apiService.getChapters("31909fc69575bf5b").enqueue(new Callback<SongciChapter>() {
            @Override
            public void onResponse(Call<SongciChapter> call, Response<SongciChapter> response) {
                if (response.isSuccessful() && response.body() != null) {
                    chapters.postValue(response.body().getResult());
                }
            }

            @Override
            public void onFailure(Call<SongciChapter> call, Throwable t) {
                // Handle failure
                chapters.postValue(null);
            }
        });
    }

    private void loadDetail(int detailid) {
        apiService.getDetail("31909fc69575bf5b", detailid).enqueue(new Callback<SongciDetail>() {
            @Override
            public void onResponse(Call<SongciDetail> call, Response<SongciDetail> response) {
                if (response.isSuccessful() && response.body() != null) {
                    detail.postValue(response.body().getResult());
                }else {
                    Log.e("ShiCiViewModel", "Failed to load detail: " + response.message());
                }
            }

            @Override
            public void onFailure(Call<SongciDetail> call, Throwable t) {
                // Handle failure
                Log.e("ShiCiViewModel", "Network failure: ", t);
                detail.postValue(null);
            }
        });
    }
}